package com.hema.auction.activity;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.apkfuns.logutils.LogUtils;
import com.hema.auction.base.BaseActivity;
import com.hema.auction.event.PayResultEvent;
import com.hema.auction.event.TabIndexEvent;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.utils.Constant;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 描述:h5支付页面
 * 作者:john
 */
public class H5PayHubActivity extends BaseActivity {

    WebView webview;
    private String payUrl, orderSn;
    private String callbackUrl = "http://www.abc.com";
    private int type;//支付类型 1充值  2我的竞拍支付 3不中包赔支付  4差价购买支付
    private boolean isInit = true;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        webview = new WebView(this);
        setContentView(webview);
        webview.setVisibility(View.GONE);
        ButterKnife.bind(this);
        showProgressDialog();
        orderSn = getIntent().getStringExtra(Constant.EXTRA_ORDER_SN);
        type = getIntent().getIntExtra(Constant.EXTRA_TYPE, 1);
        initWebView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isInit)
            HttpManager.getInstance(this).getPayStatus(orderSn, this);
        if (isInit)
            isInit = false;

    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setDomStorageEnabled(true);
        // 支持通过js打开新的窗口
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webview.setWebChromeClient(new WebChromeClient());
        webview.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                LogUtils.i("-----url = " + url);
                if (url.startsWith("weixin:") || url.startsWith("alipayqr:") || url.startsWith("alipays:")) {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
                        dismissProgressDialog();
                    } catch (ActivityNotFoundException localActivityNotFoundException) {
                        showToastSafe("请检查是否安装客户端");
                        finish();
                    }
                    return true;
                } else {
                    if (url.startsWith(callbackUrl))
                        getUrlStatus(url);
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }
        });
        payUrl = getIntent().getStringExtra(Constant.EXTRA_URL);
        webview.loadUrl(payUrl);
    }

    private void getUrlStatus(String url) {
        if (url.startsWith(callbackUrl)) {
            int status = Integer.valueOf(getParameter(url, "result"));
            if (status == 1) {
                resultForword();
                showToastSafe("支付成功");
            } else {
                showToastSafe("支付失败");
            }
            finish();
        }
    }

    private void resultForword() {
        switch (type) {
            case 1://充值
                EventBus.getDefault().post(new TabIndexEvent(3));
                screenManager.popAllActivitys(MainActivity.class);
                break;
            case 2://我的竞拍付款
                setResult(RESULT_OK);
                EventBus.getDefault().post(new PayResultEvent(type));
                break;
            case 3://不中包赔付款
                setResult(RESULT_OK);
                break;
            case 4://差价购买付款
                setResult(RESULT_OK);
                EventBus.getDefault().post(new PayResultEvent(type));
                break;
        }
    }

    /**
     * 根据url解析参数值
     *
     * @param url
     * @param key
     * @return
     */
    private String getParameter(String url, String key) {
        Uri uri = Uri.parse(url);
        return uri.getQueryParameter(key);
    }

    /**
     * 加载手机内置支付app
     *
     * @param url
     */
    private void toLoadInnerApp(String url) {
        try {
            Intent it = new Intent(Intent.ACTION_VIEW);
            it.setData(Uri.parse(url));
            startActivity(it);
        } catch (Exception e) {
            //可能情况： 手机没有安装支付宝或者微信。或者安装支付宝或者微信但是版本过低
        }
    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_GET_PAY_STATUS:
                try {
                    if (result.getInt("errcode") == 0) {
                        resultForword();
                    }
                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToastSafe("获取订单结果异常");
                }
                break;
        }
    }

    @Override
    public void onFailure(HttpTag httpTag, Call call, IOException e) {
        super.onFailure(httpTag, call, e);
        showToastSafe("获取订单结果异常");
    }

    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        dismissProgressDialog();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webview.clearHistory();
        webview.clearCache(true);
        webview.clearFormData();
        webview.destroy();
    }
}
